<template>
  <div style="padding: 10px" >
<!--    搜索区-->
    <div style="margin: 10px 0" >
      <el-input v-model="searchword" placeholder="请输入关键字" style="width: 20%" clearable ></el-input>
      <el-button type="primary"  style="margin-left: 5px" @click="this.selectUser(this.searchword)">搜索</el-button>
      <span style="margin-left: 30px">系统用户总数/授权用户数：{{totalRecord}}/{{licenseLimitUser}} </span>
<!--      <span style="margin-left: 30px">允许注册用户数：{{licenseLimitUser}}</span>-->
    </div>

    <el-table :data="tableData" border  stripe
              :cell-style="{borderColor:'#C0C0C0', fontWeight: '500', fontSize: '14px' }"
              :header-cell-style="{background: '#89D8D1',  color: '#333', fontWeight: '600', fontSize: '14px', }"
              :height="tableHeight"
    >
      <el-table-column prop="id" label="用户编号" sortable  width="150"/>
      <el-table-column prop="name" label="用户名" width="150" />
      <el-table-column prop="loginname" label="登录名" width="150"/>
      <el-table-column prop="phone" label="电话" width="200" />
      <el-table-column prop="email" label="邮箱" width="200" />

      <el-table-column label="操作"  min-width="30%" >
        <template #default="scope">
          <el-popconfirm  :title="'是否将用户 ' + scope.row.name + '的密码初始化?'"
          @confirm="handleInitPw(scope.row.id)"  >
            <template #reference>
              <el-button type="danger" >密码初始化</el-button>
            </template>
          </el-popconfirm>
          <el-button type="danger" @click="handleUpdateSpace(scope.row.id, scope.row.bak1, scope.row.name)" >文件空间调整</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        v-model:total="totalRecord"
        :small="false"
        background
        layout="total , sizes , prev, pager, next , jumper"
        :page-sizes="[15]"
        :total="0"
        @current-change="pageCurrentchange"
    >
    </el-pagination>

  </div>
</template>

<script>
// @ is an alias to /src

import request from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'SysUser',

  components: {
  },
  data(){
    return {
      tableData:[ ],
      searchword: "",
      licenseLimitUser: 0,

      currentPage :  0,
      pageSize:      15,
      totalRecord:   0,

      tableHeight:"400",

    }
  },
  mounted() {
    this.selectUser("")
    this.calculateTableHeight();
    window.addEventListener('resize', this.calculateTableHeight);
  },

  // mounted() {
  //   // this.calculateTableHeight();
  //   window.addEventListener('resize', this.calculateTableHeight);
  // },
  unmounted() {
    window.removeEventListener('resize', this.calculateTableHeight);
  },

  methods:{
    selectUser( name ){
      request.post("/sysuser/select", { name: name, pagenum : this.currentPage, pagesize : this.pageSize } ).then( res=>{
        // console.log( res )
        this.totalRecord = res.data.total
        this.currentPage = res.data.current
        this.tableData = res.data.records
        // console.log( this.tableData )

        this.licenseLimitUser = res.jsonMsg.licenseuser
      })
    },

    handleInitPw( userid ){
      request.post("/sysuser/initpw", { id: userid } ).then( res=>{
        if(res.code === "1"){
          // this.$message({ type: "success", message: res.msg })
          // console.log( res )
          ElMessageBox.alert( res.data, '密码初始化' )
        }
      })
    },

    pageCurrentchange( ){
      this.selectUser(  this.searchword )
    },

    calculateTableHeight() {
      const windowHeight = window.innerHeight;
      this.tableHeight = `${windowHeight - 200 }px`;
    },

    handleUpdateSpace(userid,  userspace, username ){
      console.log( "userspace:" , userspace )
      console.log( "spaceused: ",  this.$store.state.globalvar.spaceused )
      console.log( "spacelimit: ", this.$store.state.globalvar.spacelimit )
      var  space={}
      var spaceused
      var msg = ""


      if( userspace ){
        var s = JSON.parse( userspace )
        spaceused = s.spaceused
        msg = username + "已使用空间：<h2>"+s.spaceused.toFixed(2)+"M</h2>" +
            ""+"允许使用空间：<h2>"+ s.spacelimit +"G</h2>  请输入调整后的文件空间（G） "
      }
      else{
        spaceused = 0
        msg = username + "已使用空间：<h2>"+"0M</h2>" +
            ""+"允许使用空间：<h2>"+ this.$store.state.globalvar.spacelimitsys +"G</h2>  请输入调整后的文件空间（G） "
      }

      ElMessageBox.prompt( msg, '输入提示：', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:  /^\d*$/,
        inputErrorMessage: '只能输入数字',
        dangerouslyUseHTMLString: true,
      })
      .then(({ value }) => {
        if( !value ){
          ElMessage.error( { message: "输入不能为空!" } )
          return
        }

        space.spaceused = spaceused
        space.spacelimit = parseInt( value )
        request.get("/filespace/adjust", {params: {id: userid, space: JSON.stringify( space )  } }).then(res => {
          console.log( res )
          if( res.code === "1" ){
            var index = this.tableData.findIndex((value)=>value.id == userid );
            if(  index >= 0 )
              this.tableData[index].bak1 = JSON.stringify( space )
            ElMessage.success( { message: "更新成功!" } )
          }
          else
            ElMessage.error( { message: "更新失败!" } )
        })
      })
      .catch(() => {

      })
    },

  },  //end of methods

}
</script>



